<?php
/**
 * 将文件发送到浏览器
 * @param string $file
 * @return false|int|string
 */
function resp_file($file)
{
    //防止下载到系统文件
    $file = substr($file, 0, 1) == '/' && substr($file, 0, strlen($_SERVER['DOCUMENT_ROOT'])) != $_SERVER['DOCUMENT_ROOT'] ? $_SERVER['DOCUMENT_ROOT'] . $file : $file;
    $file = str_replace("..", "", $file);

    if ((isset($file)) && (file_exists($file))) {
        header("Content-length: " . filesize($file));
        header('Content-Type: application/octet-stream');
        header('Content-Disposition: attachment; filename="' . basename($file) . '"');
        exit(readfile("$file"));
    } else {
        exit("File Not Found!");
    }
}

/** 生成XLS文件
 * @param string $filename 文件名
 * @param string $tables_string 完整的表格
 */
function resp_xls($filename = '', $tables_string = "")
{
    if (!$filename) {
        $filename = "表格-" . now_str('', '', '');
    }
    header("Content-Type: application/vnd.ms-excel; charset=UTF-8");
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header("Content-Transfer-Encoding: binary ");
    header("Content-Disposition:attachment;filename=$filename.xls");

    $html_header = '<!doctype html><html lang="zh"><head><meta charset="UTF-8"><title></title></head><body>';
    echo $html_header . $tables_string . "<body></html>";
    exit();
}

/**
 * 开启输出缓存，用flush_outbuff输出到浏览器
 */
function start_outbuff()
{
    if (extension_loaded('zlib')) {
        ob_start('ob_gzhandler');
    }
}

/**
 * 输出缓存到浏览器
 */
function flush_outbuff()
{
    if (extension_loaded('zlib')) {
        ob_end_flush();
    }
}


//生成JSON字符串，用于状态返回
function resp_json($r, $msg = "", $data = array())
{
    $_msg = array();
    $_msg['msg'] = $msg;
    $_msg['time'] = time();
    $_msg['r'] = $r;
    $_msg['data'] = $data;
    return json_encode($_msg);
}

//生成成功的JSON字符串，用于状态返回
function resp_success_json($msg = "", $data = array())
{
    $_msg = array();
    $_msg['r'] = 1;
    $_msg['time'] = time();
    $_msg['msg'] = $msg;
    $_msg['data'] = $data;
    return json_encode($_msg);
}

//生成失败的JSON字符串，用于状态返回
function resp_error_json($msg = "", $data = array())
{
    $_msg = array();
    $_msg['r'] = 0;
    $_msg['time'] = time();
    $_msg['msg'] = $msg;
    $_msg['data'] = $data;
    return json_encode($_msg);
}


//页面跳转，可延时
function resp_goto_url($url = '', $time = 0)
{
    if (empty($url) && isset($_SERVER['HTTP_REFERER'])) {
        $url = htmlspecialchars($_SERVER['HTTP_REFERER']);
    }
    echo("<meta http-equiv=refresh content='" . $time . "; url=" . $url . "'>");
    exit();
}

/**
 * 页面定时跳转
 * @param $message
 * @param string $url
 * @param int $delay
 * @return string
 */
function resp_goto_url_message($message, $url = '', $delay = 3)
{
    if ($url == 'back') {
        $url = 'javascript:history.back()';
    } else {
        $url = htmlspecialchars($url);
    }
    $htmladd = '<meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><script>setTimeout(function() {window.location="' . $url . '"}, ' . ($delay * 1000) . ');</script>';
    echo '<div style="text-align: center"><a href="' . $url . '">' . $message . '</a></div>' . $htmladd;
    exit();
}

/**
 * 发送HTTP状态
 * @param integer $code 状态码
 * @return void
 */
function resp_http_status($code)
{
    $_status = array(
        200 => 'OK',
        301 => 'Moved Permanently',
        302 => 'Moved Temporarily ',
        400 => 'Bad Request',
        403 => 'Forbidden',
        404 => 'Not Found',
        500 => 'Internal Server Error',
        503 => 'Service Unavailable',
    );
    if (isset($_status[$code])) {
        header('HTTP/1.1 ' . $code . ' ' . $_status[$code]);
        // 确保FastCGI模式下正常
        header('Status:' . $code . ' ' . $_status[$code]);
    }
}


/**
 * 伪造404页面
 * @param bool $my404
 */
function not_found($my404 = false)
{
    resp_http_status(404);
    if ($my404 && file_exists(VDir . '404.php')) {
        $tempfile = VDir . '404.php';
        if ($tempfile) {
            include($tempfile);
        }
        exit();
    }
    exit('<!doctype html><html><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL ' . $_SERVER["SCRIPT_NAME"] . ' was not found on this server.</p></body></html>');
}

function error_page_template($title, $body)
{
    $html = <<<HTML
<!doctype html><html lang="zh"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"><meta http-equiv="X-UA-Compatible" content="ie=edge"><title>$title</title></head>
<body style="text-align: center;color: #e7041a;font-size: 1rem;">$body</body><html>
HTML;
    return $html;
}
